//
//  HJOauchViewController.swift
//  sinaWeibo
//
//  Created by hjun on 16/3/22.
//  Copyright © 2016年 hjun. All rights reserved.
//

import UIKit
import SVProgressHUD
class HJOauchViewController: UIViewController {
    
    override func loadView() {
        
        view = webview
        
        webview.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavgationBar()
        
        ///使用webview加载登陆界面
        /**  账号document.getElementById('userId').value='huangjun0529@126.com'
        
        密码
        document.getElementById('passwd').value='hjun6635937'
        
        */
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        //        print("urlString:\(urlString)")
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webview.loadRequest(request)
                
        SVProgressHUD.showWithStatus("正在加载",maskType: SVProgressHUDMaskType.None)
        
        
    }
    
    ///设置导航栏
    private func setupNavgationBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
    }
    ///导航栏点击方法 如果用private则要加@objc,否则会找不到方法
    @objc private func autoFill(){
        ///自动填充
        let JsCode = "document.getElementById('userId').value='huangjun0529@126.com';        document.getElementById('passwd').value='hjun6635937'"
        //执行Js代码
        
        webview.stringByEvaluatingJavaScriptFromString(JsCode)
        
        
    }
    
    func cancel(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    //MARK: -懒加载
    
    private lazy var webview = UIWebView()
    
}

///webview代理方法 在extension中实现
extension HJOauchViewController: UIWebViewDelegate{
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        //关闭提示
        
        SVProgressHUD.dismiss()
        
    }
    
    ///webview是否需要加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*
        
        取消
        "http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        
        授权
        "http://www.baidu.com/?code=860516c2d05fece00bf424a89c36b14e"
        
        */
        let urlString = request.URL!.absoluteString
        
        //print("urlstring: \(urlString)")
        // 当点击了取消后授权后都会加载授权回调地址,所以判断如果是授权回调地址就表示点击的是 取消 或 授权
        // 不是授权回调地址,让他加载
        if !urlString.hasPrefix(redirect_uri){
            
            return true
        }else {
            
            let query = request.URL?.query
            
            ///判断是否以code=开头
            
            let codeString = "code="
            
            if query!.hasPrefix(codeString){
                //转成字符串
                let nsQuery = query! as NSString
                //截取query里面的code
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                HJUserAccountViewModel.sharedInstance.loadAcessToken(code,completion: {(error) ->() in
                    if error != nil{
                        
                        SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                        
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            
                            self.cancel()
                        })
                        return
                    }
                    
                    print("没有错误关闭控制器")
                    self.cancel()
                    ///切换控制器
             AppDelegate.OutSwitchRootViewController(HJWecomeController())
                    
                    
                })
            }else{
                
                cancel()
            }
            
            return false
        }
        
    }
    
    
    //    func loadAcessToken(code: String){
    //    ///获取accessToken的url
    //        let urlString = "https://api.weibo.com/oauth2/access_token"
    //    ///拼接参数
    //        let parameters = [
    //
    //            "client_id" : client_id,
    //            "client_secret" : client_secret,
    //            "grant_type" : "authorization_code",
    //            "code" : code,
    //            "redirect_uri" : redirect_uri
    //
    //    ]
    //
    //        HJNetWorkTool.sharedInstance.afnMessage.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
    //
    //            print("result: \(result)")
    //
    //            
    //            }) { (_, error) -> Void in
    //                
    //                print("请求accessToken失败：\(error)")
    //        }
    //    
    //    
    //    
    //    }
    
    
}

